package com.technique.api.shop.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.technique.api.account.dao.PlaceRegisterDao;
import com.technique.api.dao.entity.Place;
import com.technique.api.dao.entity.PlaceExample;
import com.technique.api.dao.entity.PlaceRegister;
import com.technique.api.dao.entity.PlaceRegisterExample;
import com.technique.api.place.dao.PlaceDao;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Controller
@RequestMapping("/shop")
public class ShopController {

	@Autowired
	private PlaceRegisterDao placeRegisterDao;
	
	@Autowired
	private PlaceDao placeDao;
	
	@Autowired
	private ShopService shopService;
	
	@ResponseBody
	@RequestMapping(value="/register_place",method=RequestMethod.POST)
	public String registerPlace(
			long uid,
			String placeIds){
		if(StringUtils.isEmpty(placeIds)){
			throw new IllegalArgumentException("placeIds cannot be empty");
		}
		String[] idsStr = placeIds.split(",");	
		
		for(String id : idsStr){
			PlaceRegister placeRegister = new PlaceRegister();
			placeRegister.setUserId(uid);
			placeRegister.setPlaceId(Long.parseLong(id));
			placeRegister.setState(Short.parseShort("1"));
			placeRegister.setRegisterDate(new Date());
			this.placeRegisterDao.insert(placeRegister);
		}
		
		return "{\"result\":\"true\"}";
	}
	
	@ResponseBody
	@RequestMapping(value="/register_place/show")
	public String getRegisterPlace(long uid){
		
		JSONObject json = new JSONObject();
		PlaceRegisterExample example = new PlaceRegisterExample();
		example.createCriteria().andUserIdEqualTo(uid);
		List<PlaceRegister> list = this.placeRegisterDao.selectByExample(example);
		
		List<Long> ids = new ArrayList<Long>();
		for(PlaceRegister place: list){
			ids.add(place.getPlaceId());
		}
		
		
		PlaceExample placeExample = new PlaceExample();
		placeExample.createCriteria().andIdIn(ids);
		List<Place> placeList = placeDao.selectByExample(placeExample);
		
		if(placeList != null){
			JSONArray array = new JSONArray();
			for(Place place: placeList){
				JSONObject placeJson = new JSONObject();
				placeJson.put("place_id", place.getId());
				placeJson.put("name", place.getCnName());
				placeJson.put("en_name", place.getEnName());
				array.add(placeJson);
			}
			json.put("places", array);
			return json.toString();
		}else{
			return "{\"places\":[]}";
		}
		
		
	}
	

}
